import os
import subprocess
from typing import Dict, Any
try:
    from .utils import EnhancedOutput as Debug, OutputType as DebugType
except ImportError:
    from utils import EnhancedOutput as Debug, OutputType as DebugType

class FileReadTool:
    name = "file_read"
    description = "读取文件内容。支持读取任意文本文件的内容"
    parameters = {
        "type": "object",
        "properties": {
            "file_path": {
                "type": "string",
                "description": "要读取的文件路径"
            }
        },
        "required": ["file_path"]
    }

    def execute(self, args: Dict[str, Any]) -> Dict[str, Any]:
        try:
            file_path = args["file_path"]
            
            if not os.path.exists(file_path):
                return {
                    "success": False,
                    "stdout": "",
                    "stderr": f"文件不存在: {file_path}"
                }
            
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            return {
                "success": True,
                "stdout": content,
                "stderr": ""
            }
        except Exception as e:
            return {
                "success": False,
                "stdout": "",
                "stderr": f"读取文件失败: {str(e)}"
            }

class FileWriteTool:
    name = "file_write"
    description = "写入文件内容。可以将内容写入到指定文件"
    parameters = {
        "type": "object",
        "properties": {
            "file_path": {
                "type": "string",
                "description": "要写入的文件路径"
            },
            "content": {
                "type": "string",
                "description": "要写入的内容"
            }
        },
        "required": ["file_path", "content"]
    }

    def execute(self, args: Dict[str, Any]) -> Dict[str, Any]:
        try:
            file_path = args["file_path"]
            content = args["content"]
            
            # 确保目录存在
            os.makedirs(os.path.dirname(file_path), exist_ok=True)
            
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            
            return {
                "success": True,
                "stdout": f"成功写入文件: {file_path}",
                "stderr": ""
            }
        except Exception as e:
            return {
                "success": False,
                "stdout": "",
                "stderr": f"写入文件失败: {str(e)}"
            }

class DirectoryListTool:
    name = "directory_list"
    description = "列出目录内容。显示指定目录下的文件和子目录"
    parameters = {
        "type": "object",
        "properties": {
            "directory_path": {
                "type": "string",
                "description": "要列出的目录路径"
            }
        },
        "required": ["directory_path"]
    }

    def execute(self, args: Dict[str, Any]) -> Dict[str, Any]:
        try:
            directory_path = args["directory_path"]
            
            if not os.path.exists(directory_path):
                return {
                    "success": False,
                    "stdout": "",
                    "stderr": f"目录不存在: {directory_path}"
                }
            
            if not os.path.isdir(directory_path):
                return {
                    "success": False,
                    "stdout": "",
                    "stderr": f"不是目录: {directory_path}"
                }
            
            items = os.listdir(directory_path)
            items.sort()  # 按名称排序
            
            output = []
            for item in items:
                item_path = os.path.join(directory_path, item)
                if os.path.isdir(item_path):
                    output.append(f"📁 {item}/")
                else:
                    output.append(f"📄 {item}")
            
            return {
                "success": True,
                "stdout": "\n".join(output),
                "stderr": ""
            }
        except Exception as e:
            return {
                "success": False,
                "stdout": "",
                "stderr": f"列出目录失败: {str(e)}"
            }